package com.ocn.li.scmdy.modules.sys.service.impl;

import com.ocn.li.scmdy.common.utils.Constant;
import com.ocn.li.scmdy.modules.sys.dao.SysMenuDao;
import com.ocn.li.scmdy.modules.sys.dao.SysUserDao;
import com.ocn.li.scmdy.modules.sys.dao.SysUserTokenDao;
import com.ocn.li.scmdy.modules.sys.entity.SysMenuEntity;
import com.ocn.li.scmdy.modules.sys.entity.SysUserEntity;
import com.ocn.li.scmdy.modules.sys.entity.SysUserTokenEntity;
import com.ocn.li.scmdy.modules.sys.service.ShiroService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * TODO ShiroService实现类
 *
 * @author crazypenguin
 * @version 1.0.0
 * @createdate 2019/1/2
 */
@Service
public class ShiroServiceImpl implements ShiroService {
    @Autowired
    private SysMenuDao sysMenuDao;
    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private SysUserTokenDao sysUserTokenDao;

    @Override
    public Set<String> getUserPermissions(String userId) {
        List<String> permsList;

        // 系统管理员，拥有最高权限，写死ID-1
        if(userId.equals(Constant.SUPER_ADMIN) ){
            List<SysMenuEntity> menuList = sysMenuDao.selectList(null);
            permsList = new ArrayList<>(menuList.size());
            for(SysMenuEntity menu : menuList){
                permsList.add(menu.getPerms());
            }
        }else{
            permsList = sysUserDao.queryAllPerms(userId);
        }
        // 用户权限列表
        Set<String> permsSet = new HashSet<>();
        for(String perms : permsList){
            if(StringUtils.isBlank(perms)){
                continue;
            }
            permsSet.addAll(Arrays.asList(perms.trim().split(",")));
        }
        return permsSet;
    }

    @Override
    public SysUserTokenEntity queryByToken(String token) {
        return sysUserTokenDao.queryByToken(token);
    }

    @Override
    public SysUserEntity queryUser(String userId) {
        return sysUserDao.selectById(userId);
    }
}
